import { ClientSocket } from './socket/ClientSocket';
import http = require('http');
import * as WebSocket from 'ws';
import { Pool } from './Pool';
import 'com'

/**manager负责去数据库取数据，并给routes提供数据 */
export class LoginManager
{
    private static _instance:LoginManager;
    private _socket:ClientSocket;

    constructor()
    {
        this.init();
    }

    public static getInstance():LoginManager
    {
        if(this._instance == null)
        {
            this._instance = new LoginManager();
        }
        return this._instance;
    }

    private init():void
    {
        this._socket = new ClientSocket();
        this._socket.init('ws:192.168.0.246:3000');
    }

    /**解析socket请求 */
    public messageParse(msg:any):void
    {
         console.log('LoginManager.messageParse:',msg);

         //注册结果
         //登录结果
         let proto:com.BaseProto = JSON.parse(msg);

         switch(proto.head_name)
         {
             case com.HeadName.login:
                this.handleLogin(proto);
                break;
         }
    }

    public send(data):void
    {
        this._socket.send(data);
    }

    /**查询指定帐号的信息 */
    public query():void
    {

    }

    /**插入数据 */
    public insert():void
    {

    }

    /**更新指定帐号的信息 */
    public update():void
    {
        
    }

    /**去db验证 */
    public verification(base64:string,res:http.ServerResponse):void
    {

    }

    private handleLogin(proto:com.BaseProto):void
    {
        switch(proto.body_name)
        {
            case com.LoginBody.login:
                {
                    //查询回来，再compare
                    let body = proto.body;
                    let acc = body.account;
                    let obj = Pool.getInstance().getObj(acc);
                    console.log(acc + ' 查询成功');
                    let pwd = body.password;
                    obj.dbpwd = pwd;
                    obj.checkPwd().then(function(result){
                        console.warn('handleLogin.LoginBody.login:',result);
                        if(result)
                        {
                            obj.res.end('登录成功');
                        }
                        else
                        {
                            obj.res.end('登录失败');
                        }
                    }).catch(function(reason){
                        console.warn('handleLogin.LoginBody.login.err:',reason);
                        obj.res.end('登录失败',reason);
                    });
                }
                break;
            case com.LoginBody.register:
                {
                    let body = proto.body;
                    let acc = body.account;
                    let obj = Pool.getInstance().getObj(acc);
                    let res = obj.res;
                    res.end('帐号注册成功');
                    console.log(acc + ' 帐号注册成功');
                    //有了id
                    // Pool.getInstance().updateObj();
                }
                break;
        }
    }
}